﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TDS.Mail;

public partial class careers_submit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Session[GlobalSettings.CaptchaImageText] = GlobalSettings.GenerateRandomCode(4);
            hidSecurityCheck.Value = Session[GlobalSettings.CaptchaImageText].ToString();

            divAppForm.Visible = true;
            divMessage.Visible = false;
            if (MobileDeviceUtil.isMobileBrowser())
            {
                spanCV.Visible = false;
                spanFCV.Visible = false;
                rfvSummary.Enabled = true;
                revSummary.Enabled = true;
            }
            else
            {
                //spanSummary.Visible = false;
                //spanSummaryArea.Visible = false;
                rfvSummary.Enabled = false;
                revSummary.Enabled = false;
            }

            if (Request.Params["JobRefCode"] != null)
            {
                //Malaysia Aug 28 2012
                //Client Account Specialist = (MY201208280001)
                //Campaign Account Manager = (MY201208280002)
                //Project Leader = (MY20120828003)
                //Training Specialist = (MY201208280004)

                //Singapore Sep 20 2012
                //Customer Service Manager (Premium Account) = (SG201209200001)
                //Training Executive = (SG201209200002)
                //Customer Service Executive = (SG201209200003)
                //Service Quality Officer = (SG201209200004)
                //Customer Service Representatives (Inbound Calls - Airline Industry) = (SG201209200005)

                //Malaysia Jun 04 2013
                //Web Designer = (MY201306040001)

                lblFormTitle.Text = "Job Application Form";

                if (Request.Params["JobRefCode"].ToString() == "MY201208280001")
                {
                    lblFormSubTitle.Text = "Client Account Specialist @ Teledirect Malaysia";
                    lblJobRefCode.Text = "MY201208280001";
                    ddlCountry.Text = "MY";
                    ddlCountry.Enabled = false;
                }
                else if (Request.Params["JobRefCode"].ToString() == "MY201208280002")
                {
                    lblFormSubTitle.Text = "Campaign Account Manager @ Teledirect Malaysia";
                    lblJobRefCode.Text = "MY201208280002";
                    ddlCountry.Text = "MY";
                    ddlCountry.Enabled = false;
                }
                else if (Request.Params["JobRefCode"].ToString() == "MY20120828003")
                {
                    lblFormSubTitle.Text = "Project Leader @ Teledirect Malaysia";
                    lblJobRefCode.Text = "MY201208280003";
                    ddlCountry.Text = "MY";
                    ddlCountry.Enabled = false;
                }
                else if (Request.Params["JobRefCode"].ToString() == "MY201208280004")
                {
                    lblFormSubTitle.Text = "Training Specialist @ Teledirect Malaysia";
                    lblJobRefCode.Text = "MY201208280004";
                    ddlCountry.Text = "MY";
                    ddlCountry.Enabled = false;
                }

                else if (Request.Params["JobRefCode"].ToString() == "MY20130521001")
                {
                    lblFormSubTitle.Text = "Team Leader @ Teledirect Malaysia";
                    lblJobRefCode.Text = "MY20130521001";
                    ddlCountry.Text = "MY";
                    ddlCountry.Enabled = false;
                }
                else if (Request.Params["JobRefCode"].ToString() == "MY20130528001")
                {
                    lblFormSubTitle.Text = "Inside Commercial Account Manager <br/>(Thai Markets) @ Teledirect Malaysia";
                    lblJobRefCode.Text = "MY20130528001";
                    ddlCountry.Text = "MY";
                    ddlCountry.Enabled = false;
                }
                //Customer Service Manager (Premium Account) = (SG201209200001)
                else if (Request.Params["JobRefCode"].ToString() == "SG201209200001")
                {
                    lblFormSubTitle.Text = "Customer Service Manager (Premium Account) @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201209200001";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Training Executive = (SG201209200002)
                else if (Request.Params["JobRefCode"].ToString() == "SG201209200002")
                {
                    lblFormSubTitle.Text = "Training Executive @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201209200002";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Customer Service Executive = (SG201209200003)
                else if (Request.Params["JobRefCode"].ToString() == "SG201209200003")
                {
                    lblFormSubTitle.Text = "Customer Service Executive @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201209200003";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Service Quality Officer = (SG201209200004)
                else if (Request.Params["JobRefCode"].ToString() == "SG201209200004")
                {
                    lblFormSubTitle.Text = "Service Quality Officer @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201209200004";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Customer Service Representatives (Inbound Calls - Airline Industry) = (SG201209200005)
                else if (Request.Params["JobRefCode"].ToString() == "SG201209200005")
                {
                    lblFormSubTitle.Text = "Customer Service Representatives (Inbound Calls - Airline Industry) @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201209200005";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Contact Centre Specialist (Project A) - SG201301000001
                else if (Request.Params["JobRefCode"].ToString() == "SG201301000001")
                {
                    lblFormSubTitle.Text = "Contact Centre Specialist (Project A) @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201301000001";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Contact Centre Specialist (Project B) - SG201301000002
                else if (Request.Params["JobRefCode"].ToString() == "SG201301000002")
                {
                    lblFormSubTitle.Text = "Contact Centre Specialist (Project B) @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201301000002";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Contact Centre Specialist (Project C) - SG201301000003
                else if (Request.Params["JobRefCode"].ToString() == "SG201301000003")
                {
                    lblFormSubTitle.Text = "Contact Centre Specialist (Project C) @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201301000003";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Team Leader - SG201301000004
                else if (Request.Params["JobRefCode"].ToString() == "SG201301000004")
                {
                    lblFormSubTitle.Text = "Team Leader @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201301000004";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Training Executive - SG201301000005
                else if (Request.Params["JobRefCode"].ToString() == "SG201301000005")
                {
                    lblFormSubTitle.Text = "Training Executive @ Teledirect Singapore";
                    lblJobRefCode.Text = "SG201301000005";
                    ddlCountry.Text = "SG";
                    ddlCountry.Enabled = false;
                }
                //Web Designer - MY201306040001
                else if (Request.Params["JobRefCode"].ToString() == "MY201306040001")
                {
                    lblFormSubTitle.Text = "Web Designer @ Teledirect Malaysia";
                    lblJobRefCode.Text = "MY201306040001";
                    ddlCountry.Text = "MY";
                    ddlCountry.Enabled = false;
                }
                else
                {
                    lblFormTitle.Text = "Send Us Your Resume";
                    lblFormSubTitle.Text = "Deposit your CV into our talent bank";
                }
            }
            else
            {
                lblFormTitle.Text = "Send Us Your Resume";
                lblFormSubTitle.Text = "Deposit your CV into our talent bank";
            }

            //rfvCV.Enabled = false;
            if (Request.Params["say"] != null)
            {
                if (Request.Params["say"].ToString() == "thankyou")
                {
                    divAppForm.Visible = false;
                    divMessage.Visible = true;
                    lblMessage.ForeColor = System.Drawing.Color.Green;
                    lblMessage.Text = "Thanks! We have recevied your application. We will contact you if you are shortlisted. ";
                    //Page.RegisterStartupScript("JS_CompletedJobAppAlert", "alert('Thank you very much.\nOnline form was sent successfully.\nWe will reply back to you soon.');");
                    ClientScript.RegisterStartupScript(this.GetType(), "JS_CompletedJobAppAlert", "alert('" + lblMessage.Text + "');", true);
                }
            }

        }
    }


    protected void btnSubmitForm_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            try
            {
                if (txtSecurityCheck.Text.Trim().ToUpper() == hidSecurityCheck.Value.ToUpper())
                {
                    //System.Threading.Thread.Sleep(5000);
                    string _bccEmail = string.Empty;
                    MailClient _remail = new MailClient();
                    string _toEmail = System.Configuration.ConfigurationSettings.AppSettings["TDS.JobAppEmailReceiver"].ToString();

                    if (lblJobRefCode.Text.StartsWith("MY"))
                    {
                        _toEmail = System.Configuration.ConfigurationSettings.AppSettings["TDM.JobAppEmailReceiver"].ToString();
                        _bccEmail = "roy.ebiz@gmail.com;";
                    }
                    else if (lblJobRefCode.Text.StartsWith("SG"))
                    {
                        _toEmail = System.Configuration.ConfigurationSettings.AppSettings["TDS.JobAppEmailReceiverTwo"].ToString();
                    }

                    string _strCVFileName = fupCV.FileName;
                    string _strTitle = "Online Job Application Form (" + ddlTitle.SelectedItem.Text + " " + txtFullName.Text + ") at Date/Time:" + DateTime.Now.ToString("dd/MMM/yyyy hh:mm tt");

                    if (lblJobRefCode.Text.Length > 0)
                    {
                        _strTitle = lblFormSubTitle.Text + "(" + ddlTitle.SelectedItem.Text + " " + txtFullName.Text + ") at Date/Time:" + DateTime.Now.ToString("dd/MMM/yyyy hh:mm tt");
                    }

                    System.Text.StringBuilder _strBody = new System.Text.StringBuilder();
                    _strBody.Append("Dear Sir/Madam,<br/><br/>");
                    if (spanCV.Visible && spanFCV.Visible)
                    {
                        _strBody.Append("Please check following details and find enclosed CV file.<br/><br/>");
                    }
                    else
                    {
                        _strBody.Append("Please check following details.");
                    }
                    _strBody.Append("<table style=\"width:80%;\" cellspacing=\"5\" cellpadding=\"5\">");
                    if (lblJobRefCode.Text.Length > 0)
                    {
                        _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Job Title</td><td valign=\"top\">:</td><td><b>" + lblFormSubTitle.Text + "</b></td></tr>");
                        _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Job Ref. Code</td><td valign=\"top\">:</td><td><b>" + lblJobRefCode.Text + "</b></td></tr>");
                    }

                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Full Name</td><td valign=\"top\">:</td><td>" + ddlTitle.SelectedItem.Text + " " + Server.HtmlEncode(txtFullName.Text) + "</td></tr>");
                    _strBody.Append("<tr><td style=\"width:180px;\">Email Address</td><td>:</td><td>" + txtEmailAddress.Text + "</td></tr>");
                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Contact Number</td><td valign=\"top\">:</td><td>" + Server.HtmlEncode(txtContactNumber.Text.Trim()) + "</td></tr>");
                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Age</td><td valign=\"top\">:</td><td>" + txtAge.Text + "</td></tr>");
                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Qualification</td><td valign=\"top\">:</td><td>" + Server.HtmlEncode(txtQualification.Text.Trim()) + "</td></tr>");
                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">No of Years of Experience</td><td valign=\"top\">:</td><td>" + ddlExpYear.SelectedItem.Text + "</td></tr>");
                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Sales Experience</td><td valign=\"top\">:</td><td>" + ddlSaleExp.SelectedItem.Text + "</td></tr>");
                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Employment Status</td><td valign=\"top\">:</td><td>" + ddlEmpStatus.SelectedItem.Text + "</td></tr>");
                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Preferred Country</td><td valign=\"top\">:</td><td>" + ddlCountry.SelectedItem.Text + "</td></tr>");
                    
                    //if (spanCV.Visible && spanFCV.Visible && fupCV.HasFile)
                    //{
                    //    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Original File Name</td><td valign=\"top\">:</td><td>" + fupCV.FileName + "</td></tr>");
                    //}
                    //else
                    //{
                    //    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Summary</td><td valign=\"top\">:</td><td>" + Server.HtmlEncode(txtSummary.Text.Trim()).Replace("\r\n", "<br/>") + "</td></tr>");
                    //}

                    _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Original File Name</td><td valign=\"top\">:</td><td>" + fupCV.FileName + "</td></tr>");
                    if (txtSummary.Text.Trim().Length > 0)
                    {
                        _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Comments</td><td valign=\"top\">:</td><td>" + Server.HtmlEncode(txtSummary.Text.Trim()).Replace("\r\n", "<br/>") + "</td></tr>");
                    }
                    else
                    {
                        _strBody.Append("<tr><td style=\"width:180px;\" valign=\"top\">Comments</td><td valign=\"top\">:</td><td>No comments.</td></tr>");
                    }

                    _strBody.Append("</table>");

                    string _uploadFilePath = string.Empty;

                    if (spanCV.Visible && spanFCV.Visible && UploadFile(out _uploadFilePath))
                    {
                        string[] fileList = new string[1];
                        if (_uploadFilePath != string.Empty)
                        {
                            fileList[0] = _uploadFilePath;
                        }

                        if (_remail.SendNetNoreplyMailByAttachements(_strTitle, _strBody.ToString(), "Teledirect Online Job Application", "Teledirect HR", _toEmail, string.Empty, _bccEmail, fileList))
                        {
                            Response.Redirect("submit.aspx?say=thankyou");
                        }
                        else
                        {
                            divMessage.Visible = true;
                            lblMessage.Text = "Error found! Failed to send message.<br/>Pleas try again it later.";
                            lblMessage.Font.Bold = true;
                            lblMessage.ForeColor = System.Drawing.Color.Red;
                        }
                    }
                    else
                    {
                        if (_remail.SendNetNoreplyMail(_strTitle, _strBody.ToString(), "Teledirect Online Job Application", "Teledirect HR", _toEmail, string.Empty, _bccEmail))
                        {
                            Response.Redirect("submit.aspx?say=thankyou");
                        }
                        else
                        {
                            divMessage.Visible = true;
                            lblMessage.Text = "Error found! Failed to send message.<br/>Pleas try again it later.";
                            lblMessage.Font.Bold = true;
                            lblMessage.ForeColor = System.Drawing.Color.Red;
                        }
                    }
                }
                else
                {
                    divMessage.Visible = true;
                    lblMessage.Text = "Wrong security check code. Please try again!";
                    lblMessage.Font.Bold = true;
                    lblMessage.ForeColor = System.Drawing.Color.Red;

                    Session[GlobalSettings.CaptchaImageText] = GlobalSettings.GenerateRandomCode(4);
                    hidSecurityCheck.Value = Session[GlobalSettings.CaptchaImageText].ToString();
                    //lblMessage.Text = "Encrypt:" + hidSecurityCheck.Value.ToString() + ", Decrypt:" + MOC.Utilities.Security.MySecurity.Decrypt(hidSecurityCheck.Value.ToString(), true);
                }

            }
            catch (Exception Ex)
            {
                divMessage.Visible = true;
                lblMessage.Text = "Error found! Please try it later again.<br/>" + Ex.Message;
                lblMessage.Font.Bold = true;
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
    }

    private bool UploadFile(out string filePath)
    {
        bool _retValue = false;

        filePath = string.Empty;

        try
        {
            TDS.IO.FileSystem _newFile = new TDS.IO.FileSystem();
            if (fupCV.HasFile)
            {
                HttpPostedFile _postFile = fupCV.PostedFile;

                int _fileLen = 0;

                if (_postFile.ContentLength > 0)
                {
                    _fileLen = _postFile.ContentLength / 1024;
                }

                string _fileName = _postFile.FileName;
                string _fileExt = System.IO.Path.GetExtension(_fileName).ToLower();
                bool _fileExtValid = false;

                string[] _arrFileExt = System.Configuration.ConfigurationManager.AppSettings["TDS.CVUploadFileExt"].Split(',');
                int _fileSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TDS.CVUploadFileSizeKB"]);

                for (int i = 0; i < _arrFileExt.Length; i++)
                {
                    if (_fileExt == _arrFileExt[i])
                    {
                        _fileExtValid = true;
                        break;
                    }
                }

                if (_fileExtValid)
                {
                    if (_fileLen > 0 && _fileLen <= _fileSize)
                    {
                        //string _filePath = AppDomain.CurrentDomain.BaseDirectory + "TDSCVUploadFiles\\";
                        string _filePath = System.Configuration.ConfigurationManager.AppSettings["TDS.CVUploadFilePath"];
                        if (_newFile.CheckDirectory(_filePath))
                        {
                            string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                            if (!_newFile.CheckDirectory(_filePath + _curMonth))
                            {
                                if (_newFile.CreateDirectory(_filePath, _curMonth))
                                {
                                    _filePath += _curMonth + "\\";
                                }
                            }
                            else
                            {
                                _filePath += _curMonth + "\\";
                            }

                            string _curDate = DateTime.Now.ToString("ddMMMyyyy");

                            if (!_newFile.CheckDirectory(_filePath + _curDate))
                            {
                                if (_newFile.CreateDirectory(_filePath, _curDate))
                                {
                                    _filePath += _curDate + "\\";
                                }
                            }
                            else
                            {
                                _filePath += _curDate + "\\";
                            }

                            filePath = _filePath + "JobApp_" + DateTime.Now.ToString("ddMMMyyyy_hhmmss_tt") + _fileExt;

                            fupCV.SaveAs(filePath);

                            _retValue = true;
                            //_newFile.WriteNewFile(_filePath, _fileName, strException);
                            _newFile = null;
                        }
                    }
                    else
                    {
                        lblUploadMessage.Text = "<br/>Invalid or File size is over limit.";
                    }
                }
                else
                {
                    lblUploadMessage.Text = "<br/>Invalid file type.";
                }
            }
            //else
            //{
            //    //Mobile Device
            //    _retValue = !rfvCV.Enabled;
            //}
        }
        catch (Exception Ex)
        {
            lblUploadMessage.Text = "<br/>" + Ex.Message;
        }

        return _retValue;
    }

}
